package com.chenjiahao.kaiyanwan.logic.network

import com.hazz.kotlinmvp.mvp.model.bean.HomeBean
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.await
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object ServiceNetwork {
    private val kaiyanService = ServiceCreator.create<ApiService>()

    suspend fun getFirstHomeData(num: Int) = kaiyanService.getFirstHomeData(num).await()
    suspend fun getMoreHomeData(url: String) = kaiyanService.getMoreHomeData(url).await()
    suspend fun getRelatedData(id: Long) = kaiyanService.getRelatedData(id).await()
    suspend fun getSearchData(string: String) = kaiyanService.getSearchData(string).await()
    suspend fun getIssueData(string: String) = kaiyanService.getIssueData(string).await()
    suspend fun getHotWord() = kaiyanService.getHotWord().await()
    suspend fun getCategory() = kaiyanService.getCategory().await()
    suspend fun getFollowInfo() = kaiyanService.getFollowInfo().await()
    suspend fun getCategoryDetailList(id: Long) = kaiyanService.getCategoryDetailList(id).await()
    suspend fun getRankList() = kaiyanService.getRankList().await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(RuntimeException("response body is null"))
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }


}